package day17;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

//基于Lock锁实现购票功能
public class Demo6 {
    int sum=100;
    ReentrantLock lock=new ReentrantLock();
    public void buy() throws InterruptedException {
        String name=Thread.currentThread().getName();
        //手动加锁
        //lock(): 手动加锁，如果锁一值竞争不到 会一致等待
        //tryLock(): 尝试获取锁 如果获取不到 直接放弃
        //tryLock(时间,单位): 尝试获取锁的时间 如果时间到了还获取不到 则不要了
        if(lock.tryLock(1, TimeUnit.SECONDS)){
            try {
                if(sum>0){
                    sum--;
                    Thread.sleep(100);
                    System.out.println(name+"购买成功,剩余:"+sum);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //手动释放锁:适合放在finally编写
                lock.unlock();
            }
        }else{
            System.out.println(name+"1秒获取不到锁 我放弃了");
        }
    }
    public static void main(String[] args) {
        Demo6 d=new Demo6();
        new Thread(()->{
            for(int i=0;i<100;i++){
                try {
                    d.buy();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"志广").start();
        new Thread(()->{
            for(int i=0;i<100;i++){
                try {
                    d.buy();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"万鑫").start();
    }
}